<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="预制菜" prop="recipePremaidFoodId">
        <!-- <el-input
          v-model="queryParams.recipePremaidFoodId"
          placeholder="请输入预制菜"
          clearable
          @keyup.enter.native="handleQuery"
        /> -->
        <el-select
          v-model="queryParams.recipePremaidFoodId"
          placeholder="请选择预制菜"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="food in premaidFoodOptions"
            :key="food.premaidFoodId"
            :label="food.premaidFoodName"
            :value="food.premaidFoodId"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:recipe:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:recipe:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:recipe:remove']"
        >删除</el-button>
      </el-col>
    <!--  <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:recipe:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- <el-table v-loading="loading" :data="recipeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="配方id" align="center" prop="recipeId" />
      <el-table-column label="预制菜id" align="center" prop="recipePremaidFoodId" />
      <el-table-column label="原材料id" align="center" prop="recipeRawMaterilaId" />
      <el-table-column label="原材料需求量" align="center" prop="recipeCount" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:recipe:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:recipe:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table> -->
    <el-table
      v-loading="loading"
      :data="groupedRecipeList"
      row-key="uniqueKey"
      :tree-props="{children: 'materials', hasChildren: 'hasChildren'}"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="预制菜名称" prop="premaidFoodName" width="180">
        <template slot-scope="scope">
          <span v-if="!scope.row.recipeId">{{ scope.row.premaidFoodName }}</span>
          <span v-else>{{ scope.row.rawMaterialName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="原材料" prop="rawMaterialName" width="180" v-if="false" />
      <el-table-column label="需求量" prop="recipeCount" align="center" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.recipeId"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:recipe:edit']"
          >修改</el-button>
          <el-button
            v-if="scope.row.recipeId"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:recipe:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改配方管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="预制菜" prop="recipePremaidFoodId">
          <el-select
            v-model="form.recipePremaidFoodId"
            placeholder="请选择预制菜"
            filterable
            clearable
            style="width: 100%"
            @change="handleFoodChange"
          >
            <el-option
              v-for="food in premaidFoodOptions"
              :key="food.premaidFoodId"
              :label="food.premaidFoodName"
              :value="food.premaidFoodId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="原材料" prop="recipeRawMaterilaId">
          <el-select
            v-model="form.recipeRawMaterilaId"
            placeholder="请选择原材料"
            filterable
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="material in rawMaterialOptions"
              :key="material.rawMaterialId"
              :label="material.rawMaterialName"
              :value="material.rawMaterialId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="需求量" prop="recipeCount">
          <el-input-number
            v-model="form.recipeCount"
            :min="1"
            :precision="0"
            controls-position="right"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
      <!-- <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="预制菜" prop="recipePremaidFoodId">
          <el-select
            v-model="form.recipePremaidFoodId"
            placeholder="请选择预制菜"
            filterable
            clearable
            style="width: 100%"
            @change="handleFoodChange"
          >
            <el-option
              v-for="food in premaidFoodOptions"
              :key="food.premaidFoodId"
              :label="food.premaidFoodName"
              :value="food.premaidFoodId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="原材料" prop="recipeRawMaterilaId">
          <el-select
            v-model="form.recipeRawMaterilaId"
            placeholder="请选择原材料"
            filterable
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="material in rawMaterialOptions"
              :key="material.rawMaterialId"
              :label="material.rawMaterialName"
              :value="material.rawMaterialId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="需求量" prop="recipeCount">
          <el-input-number
            v-model="form.recipeCount"
            :min="1"
            :precision="0"
            controls-position="right"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div> -->
    </el-dialog>
  </div>
</template>

<script>
import { listRecipe, getRecipe, delRecipe, addRecipe, updateRecipe } from "@/api/system/recipe";
import { listFood } from "@/api/system/food";
import { listMaterial } from "@/api/system/material";
export default {
  name: "Recipe",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 配方管理表格数据
      recipeList: [],
      // 分组后的配方列表
      groupedRecipeList: [],
      // 预制菜选项
      premaidFoodOptions: [],
      // 原材料选项
      rawMaterialOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        recipePremaidFoodId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        recipePremaidFoodId: [
          { required: true, message: "请选择预制菜", trigger: "change" }
        ],
        recipeRawMaterilaId: [
          { required: true, message: "请选择原材料", trigger: "change" }
        ],
        recipeCount: [
          { required: true, message: "请输入需求量", trigger: "blur" },
          { type: "number", min: 1, message: "需求量必须大于0" }
        ]
      }
    };
  },
  async created() {
    // 使用Promise.all等待所有前置请求完成
    await Promise.all([
      this.loadPremaidFoodOptions(),
      this.loadRawMaterialOptions()
    ]);

    // 确保前置数据加载完成后再获取列表
    await this.getList();
  },
  methods: {

    /** 加载预制菜下拉选项 */
    async loadPremaidFoodOptions() {
      try {
        const response = await listFood();
        this.premaidFoodOptions = response.rows;
        return true; // 返回成功状态
      } catch (error) {
        console.error('加载预制菜选项失败:', error);
        return false;
      }
    },
    /** 加载原材料下拉选项 */
    async loadRawMaterialOptions() {
      try {
        const response = await listMaterial();
        this.rawMaterialOptions = response.rows;
        return true; // 返回成功状态
      } catch (error) {
        console.error('加载原材料选项失败:', error);
        return false;
      }
    },
    /** 预制菜选择变化 */
    handleFoodChange(foodId) {
      if (foodId) {
        const selectedFood = this.premaidFoodOptions.find(food => food.premaidFoodId == foodId);
        this.form.premaidFoodName = selectedFood ? selectedFood.premaidFoodName : '';
      } else {
        this.form.premaidFoodName = '';
      }
    },

    /** 查询配方管理列表 */
    async getList() {
      this.loading = true;
      try {
        const response = await listRecipe(this.queryParams);
        this.recipeList = response.rows;
        this.total = response.total;
        this.groupRecipes();
      } catch (error) {
        console.error('获取配方列表失败:', error);
      } finally {
        this.loading = false;
      }
    },
    /** 将配方数据按预制菜分组 */
    groupRecipes() {
      const grouped = {};

      this.recipeList.forEach(recipe => {
         // 查找预制菜名称（优先从预加载的选项获取）
        const foodItem = this.premaidFoodOptions.find(
          food => food.premaidFoodId == recipe.recipePremaidFoodId
        );
        if (!grouped[recipe.recipePremaidFoodId]) {
          grouped[recipe.recipePremaidFoodId] = {
            uniqueKey: `group-${recipe.recipePremaidFoodId}`, // 添加唯一键
            premaidFoodId: recipe.recipePremaidFoodId,
            premaidFoodName: foodItem?.premaidFoodName || '未知预制菜',
            materials: []
          };
        }

        // 同样处理原材料名称
        const materialItem = this.rawMaterialOptions.find(
          mat => mat.rawMaterialId === recipe.recipeRawMaterilaId
        );
        grouped[recipe.recipePremaidFoodId].materials.push({
          ...recipe,
          uniqueKey: `item-${recipe.recipeId}`,  // 添加唯一键
          rawMaterialName: materialItem?.rawMaterialName || '未知原材料'
        });
      });

      this.groupedRecipeList = Object.values(grouped);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        recipeId: null,
        recipePremaidFoodId: null,
        recipeRawMaterilaId: null,

        recipeCount: 1,
        premaidFoodName: '',
        rawMaterialName: ''
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.recipePremaidFoodId = null;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.filter(item => item.recipeId).map(item => item.recipeId);
      this.single = this.ids.length !== 1;
      this.multiple = !this.ids.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加配方管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const recipeId = row.recipeId || this.ids
      getRecipe(recipeId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改配方管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.recipeId != null) {
            updateRecipe(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRecipe(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const recipeIds = row.recipeId || this.ids;
      this.$modal.confirm('是否确认删除选中的配方？' ).then(function() {
        return delRecipe(recipeIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/recipe/export', {
        ...this.queryParams
      }, `recipe_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>
.el-table ::v-deep .el-table__row--level-0 {
  font-weight: bold;
  background-color: #f5f7fa;
}
</style>
